const mqtt = require('mqtt');
 
const client = mqtt.connect('ws://127.0.0.1:1882');
const _topic = 'fastsearch/';
client.on('connect', function() {
    console.log('Connected to MQTT Broker');
    client.subscribe(_topic+'#');
    setInterval(() => {
        publish();
    }, 1000);
});
 
client.on('message', function(topic, message) {
    // message is Buffer
    console.log("收到消息",message.toString(),"来自",topic);
});
 
client.on('error', function(err) {
    console.log(err);
});

  //发布消息
  function publish(){
    const message={
        id:'sn-'+Math.random(),
        text:'Hellow'+Math.random()+new Date()
    }

    client.publish(_topic+Math.random(),JSON.stringify(message),{qos : 2})
    console.log("发布消息成功....."+message)
  }